import { Component, OnInit, OnDestroy } from '@angular/core';
import { Http } from '@angular/http';
import { Channel } from '../../utils/channel';
import { AlertsService } from '../../modules/ng2-alerts';

import { Router } from '@angular/router';

@Component({
  selector: 'app-forget',
  templateUrl: './forget.page.html',
  styleUrls: ['./forget.page.css'],
  providers: [Channel]
})
export class ForgetPage implements OnInit {

  // 登录错误提示
  public error: boolean = false;

  // user
  public user: any;

  public source: any;

  eventOff: any;

  eventCodeOff: any;

  constructor(private channel: Channel, private http: Http, private _alert: AlertsService, private router: Router) { }

  ngOnInit() {
    // user
    this.user = {
      nick: '',
      password: '',
      channel: 0,
      code: '',
      codeText: '获取验证码',
      nickError: false,
      codeError: false
    };

    this.source = this.channel.init();

    this.user.channel = this.source.channel;
  }

  ngOnDestroy() {

    if (this.eventCodeOff) {
      this.eventCodeOff.unsubscribe();
    }

    if (this.eventOff) {
      this.eventOff.unsubscribe();
    }
  }

  // 获取验证码
  getCode() {
    if (this.user.nickError) {
      this.user.nickError = false;
    }
    this.user.codeText = '60秒...';
    this.time();

    this.eventCodeOff = this.http.post('/qbmf/sendVerifySMS', {
      type: 1,
      phone: this.user.nick,
      channel: this.user.channel
    }).subscribe((res: any) => {
      // console.log(res);

    }, (err: any) => {
      // console.log(err);
      // this._alert.create('info',  err.error.msg);
      this.user.nickError = true;

    });



    return false;
  }

  // 倒计时
  timeLimit = 60;
  time() {
    setTimeout(() => {

      this.timeLimit -= 1;


      if (this.timeLimit > 0) {

        this.user.codeText = this.timeLimit + '秒...';

        this.time();
      } else {
        this.user.codeText = "获取验证码";
        this.timeLimit = 60;
      }


    }, 1000);
  }

  submit() {

    if (this.user.codeError) {
      this.user.codeError = false;
    }
    this.eventOff = this.http.post('/qbmf/updatePassword', {
      nick: this.user.nick,
      code: this.user.code,
      password: this.user.password,
      channel: this.user.channel
    }).subscribe((res: any) => {
      // console.log(res);

      this._alert.create('success', "密码重置成功");

      setTimeout(() => {
        this.router.navigate(['/login']);
      }, 1000);

    }, (err: any) => {
      // console.log(err);
      //
      this.user.codeError = true;

    });
  }

}
